import {
  Button,
  Cell,
  Dialog,
  Popup,
} from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";
import styles from "./index.scss";
import { useRequest } from "taro-hooks";
import { deleteFamily, getFamilyList, quitFamily } from "@/services/Family";
import { useRef, useState } from "react";
import Add from "./Add";
import { Check } from "@nutui/icons-react-taro";
import { useFamilyStore } from "@/model";
import Taro, { showToast } from "@tarojs/taro";
import JoinFamily from "./JoinFamily";
import { isMeById } from "@/utils/token";
import Tag from "@/components/Tag";

export default () => {
  const { data, run } = useRequest(getFamilyList);
  const { family, setFamily } = useFamilyStore();
  const [open, setOpen] = useState(false);
  const [showPopup, setShowPopup] = useState(false);
  const [delOpen, setDelOpen] = useState(false);
  const [quitOpen,setQuitOpen] =useState(false);
  const editInfo = useRef<API.FamilyUserInfo>({});
  const { run: del } = useRequest(deleteFamily, {
    manual: true,
    onSuccess: (res, [{ id }]) => {
      showToast({
        title: "删除成功",
        icon: "none",
      });
      if (id === family?.id) {
        setFamily({});
      }
      setShowPopup(false);
      run({});
    },
    onFinally: () => {
      setDelOpen(false);
    },
  });
  const { run: quit } = useRequest(quitFamily, {
    manual: true,
    onSuccess: (res, [familyId]) => {
      showToast({
        title: "退出成功",
        icon: "none",
      });
      if (familyId === family?.id) {
        setFamily({});
      }
      setShowPopup(false);
      run({});
    },
    onFinally: () => {
      setQuitOpen(false);
    },
  });
  return (
    <View className={styles.container}>
      <Button
        className={styles.btn}
        onClick={() => {
          editInfo.current = {};
          setOpen(true);
        }}
      >
        创建家庭
      </Button>
      <JoinFamily refresh={run} />
      {data?.length === 0 && "暂无家庭，快去创建吧！"}
      {data?.map?.((item, index) => (
        <Cell
          title={item.name}
          description={
            <View>
              <View>
                {item.description}{" "}
                {isMeById(item.userId) && <Tag type="info">我的</Tag>}
              </View>
            </View>
          }
          onClick={() => {
            editInfo.current = {
              id: item.id,
              name: item.name,
              description: item.description,
              userId: item.userId,
            };
            setShowPopup(true);
          }}
          extra={family?.id === item?.id && <Check />}
          key={index}
        />
      ))}
      <Popup
        visible={showPopup}
        position="bottom"
        onClose={() => {
          setShowPopup(false);
        }}
      >
        {family?.id !== editInfo.current?.id && (
          <Cell
            className={styles.btn}
            onClick={() => {
              setFamily(editInfo.current);
              setShowPopup(false);
              Taro.switchTab({ url: "/pages/home/index" });
            }}
          >
            设为当前家庭
          </Cell>
        )}
        {isMeById(editInfo.current?.userId) && (
          <Cell
            className={styles.btn}
            onClick={() => {
              setOpen(true);
            }}
          >
            编辑
          </Cell>
        )}
        {isMeById(editInfo.current?.userId) ? (
          <Cell
            className={styles.btn}
            onClick={() => {
              setDelOpen(true);
            }}
          >
            删除
          </Cell>
        ) : <Cell
          className={styles.btn}
          onClick={() => {
            setQuitOpen(true)
          }}
        >
          退出家庭
        </Cell>}

        <Cell
          className={styles.btn}
          onClick={() => {
            setShowPopup(false);
          }}
        >
          取消
        </Cell>
      </Popup>

      <Add
        info={editInfo.current}
        open={open}
        refresh={run}
        onClose={() => {
          setOpen(false);
        }}
      />
      <Dialog
        title="确认删除该家庭？"
        visible={delOpen}
        onConfirm={() => {
          del({ id: editInfo.current.id });
        }}
        onCancel={() => {
          setDelOpen(false);
        }}
      />
      <Dialog
        title="确认退出该家庭？"
        visible={quitOpen}
        onConfirm={() => {
          quit(editInfo.current.id);
        }}
        onCancel={() => {
          setQuitOpen(false);
        }}
      />
    </View>
  );
};
